package com.roncoo.education.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.roncoo.education.api.request.ProductRequest;
import com.roncoo.education.api.response.ProductResponse;
import com.roncoo.education.db.entity.Product;
import com.roncoo.education.db.service.MyHistoryService;
import com.roncoo.education.db.service.ProductService;
import com.roncoo.education.util.MyJwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class ProductController {

    @Resource
    private ProductService productService;

    @Resource
    MyHistoryService myHistoryService;

    @Resource
    MyJwtUtil myJwtUtil;

    @PostMapping("/getProdPage")
    public String getProdPage(@Valid @RequestBody ProductRequest req){
        PageInfo<Product> pageInfo = productService.getProdPages(req);
        return JSONUtil.toJsonStr(pageInfo);
    }

    @GetMapping("/prodList")
    public String prodList(Integer saleFlag){
        List<Product> pageInfo = productService.getProdsList(saleFlag);
        return JSONUtil.toJsonStr(pageInfo);
    }

    @GetMapping("/getProd")
    public String getProdDetail(Long id, HttpServletRequest request){
        ProductResponse news = productService.getProductById(id);
        String token = request.getHeader("token");
        if(StrUtil.isNotBlank(token)) {
            Long userId = myJwtUtil.getUsernameFromToken(token);
            myHistoryService.saveHistory(userId, id, 2);
        }
        if(news!=null){
            productService.getProdAddViews(news.getId(), news.getViews());
        }
        return JSONUtil.toJsonStr(news);
    }
}
